from django.utils import timezone
from django import http

from users.models import User
from rest_framework import serializers

class AdminAuthSerializers(serializers.ModelSerializer):
    '''用户名可以默认生成，但是默认生成的会在数据库中验证是否存在，存在则报错，所以需要自己定义'''
    token = serializers.CharField(label='jwt_token',read_only=True)
    username = serializers.CharField(label='用户名')
    class Meta():
        model = User
        fields = ('id','username','password','token')
        extra_kwargs = {
            'password':{
                'write_only':True
            }
        }
    def validate(self, attrs):
        username = attrs['username']
        password = attrs['password']
        try:
            user = User.objects.get(username=username,is_staff=True)
        except User.DoesNotExist:
            raise serializers.ValidationError('用户名或密码错误')
        else:
            '''校验密码是否正确'''
            if not user.check_password(password):
                raise serializers.ValidationError('用户名或密码错误')
            '''在attrs中添加user'''
            attrs['user']=user
        return attrs
    '''2. 服务器签发jwt token数据'''
    def create(self, validated_data):
        '''获取user'''
        user = validated_data['user']
        '''更新最新登陆时间'''
        new_time=timezone.now()
        user.last_login = new_time
        user.save()
        '''手动生成jwt token'''
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user